<?php

namespace app\home\controller;

use think\Controller;
use app\common\base\curl;
use think\Db;
use vehicle\signvehicle;
use app\common\base\_Db;
use think\Cache;

class Interapi extends Controller{
    public function Index(){
        $JsonData = file_get_contents('php://input');
        $JsonData = json_decode($JsonData,true);
        $day_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        switch ($JsonData['type']){
            case 'fee':
                if($JsonData['iden'] == (int)2||$JsonData['iden'] == (int)4){
                    //是员工的状态下
                    //不允许一个员工在单位时间内多次刷卡，时间间䣓暂定30分钟
                    $res = Db::table('free_order')
                        ->where('iden = 2 and uid = '.$JsonData['uid'].' and time >"'.date('Y-m-d',$day_time).' 00:00:00"')
                        ->order('time desc')->limit(1)->select();
                    if (!empty($res) && (time()-strtotime($res[0]['time'])<1800)){
                        return json_encode(['code'=>'1000','msg'=>'不允许重复刷卡']);
                    }
                    $data = [
                        'uid'=>$JsonData['uid'],
                        'iden'=>(int)2,
                        'money'=>(int)$JsonData['price'],
                        'line_id'=>(int)$JsonData['line'],
                        'time'=>date('Y-m-d H:i:s',time()),
                        'deviceid'=>$JsonData['DeviceId']
                    ];
                   if( Db::name('free_order')->insert($data) ){
                       return json_encode(['code'=>'200','msg'=>'OK']);
                   }else{
                       return json_encode(['code'=>'1000','msg'=>'失败']);
                   }
                }elseif($JsonData['iden'] == (int)1){
                    //客户免密支付
                    if(time() - $JsonData['cardTime'] > 60){
                        return json_encode(['code'=>'1000','msg'=>'支付失败']);
                    }
                   $res = $this->payapply($JsonData['uid'],$JsonData['OutTradeNo'],$JsonData['price']*100);
                   if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                       Db::name('order_info')
                           ->insert(
                               [
                                   'pay_money'=>$JsonData['price'],
                                   'line_id'=>(int)$JsonData['line'],
                                   'deviceid'=>$JsonData['DeviceId'],
                                   'out_trade_no'=>$JsonData['OutTradeNo'],
                                   'openid'=>$this->GetOpenId($JsonData['uid']),
                                   'pay_time'=>date('Y-m-d H:i:s',time()),
                                   'trade_state'=>(int)2
                               ]
                           );
                       return json_encode(['code'=>'200','msg'=>'OK']);
                   }else{
                       return json_encode(['code'=>'1000','msg'=>'支付失败']);
                   }
                }elseif ($JsonData['iden'] == (int)3){
                    //不允许一个员工在单位时间内多次刷卡，时间间䣓暂定30分钟
                    $res = Db::table('free_order')
                        ->where('iden = 3 and uid = '.$JsonData['uid'].' and time >"'.date('Y-m-d',$day_time).' 00:00:00"')
                        ->order('time desc')->limit(1)->select();
                    if (!empty($res) && (time()-strtotime($res[0]['time'])<1800)){
                        return json_encode(['code'=>'1000','msg'=>'不允许重复刷卡']);
                    }
                    $data = [
                        'uid'=>$JsonData['uid'],
                        'iden'=>(int)3,
                        'money'=>(int)$JsonData['price'],
                        'line_id'=>(int)$JsonData['line'],
                        'time'=>date('Y-m-d H:i:s',time()),
                        'deviceid'=>$JsonData['DeviceId']
                    ];
                    if( Db::name('free_order')->insert($data) ){
                        return json_encode(['code'=>'200','msg'=>'OK']);
                    }else{
                        return json_encode(['code'=>'1000','msg'=>'失败']);
                    }
                }
                break;
            case 'driver':
                   //根据线路id 更新其他信息
                $uid = $JsonData['cardTime'];
                $DeviceId = $JsonData['DeviceId'];//设备号
                $day_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $driver_bus = Db::table('bus_driver')
                    ->where('deviceid = "'.$DeviceId .'" and oper_time >= "'.$day_time.'"')->order('oper_time desc')->limit(1)->find();
                if (empty($driver_bus)||(!empty($driver_bus)&&(time()-$driver_bus['oper_time'])>1200)){
                    if(
                    Db::name('bus_info')
                        ->where('vehicle_device_id ="'.$JsonData['DeviceId'].'"')
                        ->update([
                            'line_id'=>$JsonData['line'],
                            'oper_date'=>date('Y-m-d H:i:s',time())
                        ])
                    ){
                        //先查询再绑定
                        /*司机绑定线路及车辆,按线路同一设备二十分钟绑定一个人,二十分钟后重新统计*/
                        $ins = [
                            'deviceid'    =>$JsonData['DeviceId'],
                            'staff_id'    =>$JsonData['cardTime'],
                            'oper_time'   =>time(),
                        ];
                        Db::table('bus_driver')->insert($ins);

                        return json_encode(['code'=>'200','msg'=>'切换线路成功']);
                    }else{

                        return json_encode(['code'=>'1000','msg'=>'OK']);
                    }
                }

                break;
        }
    }
    public function curl(){
        $res=['data'=>
                [
                'uid'         => '1',
                'cardTime'    => time(),
                'iden'        => 1, //用户身份
                'type'        => 'post', //判断参数
                'OutTradeNo'  => '11111111' //订单流水号
                ]
        ];
        $res = json_encode($res);
        curl::PostUrl('http://airport.xuejiuhui.net/home/interapi/index',$res);
    }

    /*       半小时内不能重复乘车
     *       $difftime = $this->timediff($this->Lasttime($JsonData['uid'],$JsonData['iden']),$JsonData['cardTime']);
                    if($difftime > (int)30){
                        return ResponseJson::Json(['code'=>201,'msg'=>'Not OK']);
                    }
     */

    public function Lasttime($id,$iden){
        switch ($iden){
            case 2:
                $openid = Db::name('staff')
                    ->field('openid')
                    ->where('staff_id ='.$id)
                    ->find();
                $openid = $openid['openid'];
                break;
            case 1:
                $openid = Db::name('user')
                    ->field('openid')
                    ->where('user_id ='.$id)
                    ->find();
                $openid = $openid['openid'];
                break;
            case 3:
                $openid = Db::name('external_staff')
                    ->field('openid')
                    ->where('id ='.$id)
                    ->find();
                $openid = $openid['openid'];
                break;
        }
        $time = Db::name('order_info')
            ->field('pay_time')
            ->where('openid ='.$openid)
            ->order('pay_time desc')
            ->limit(1)
            ->find();
        $time = $time['pay_time'];
        return $time;
    }
    function timediff($begin_time,$end_time)
    {
        $timediff = $begin_time-$end_time;
        //计算小时数
        $remain = $timediff%86400;
        //计算分钟数
        $remain = $remain%3600;
        $mins = $remain/60;
        return $mins;
    }


    //BUG申请扣费
    public function payapply($uid,$orderno,$money){
        $result = _Db::GetData('user',array('user_id'=>'uid','openid'=>'openid','sign_contract_id'=>'sign_contract_id'),'user_id = '.$uid);
        $url = 'https://api.mch.weixin.qq.com/transit/partnerpay/payapply';
        $scene_info=[
            'start_time'=>date('YmdHis'),  //扣费时间
        ];
        $post_data = [
            'appid'=>pay_config()['appid'], //服务商appid
            'mch_id'=>pay_config()['mch_id'], // 服务商商户号
            'sub_mch_id'=>pay_config()['sub_mch_id'], //子商户号
            'nonce_str'     =>'5K8264ILTKCHCQ5011SI8ZNMTM67VS', //
            'sign_type'     =>'HMAC-SHA256', //签名类型
            'body' =>'公交代扣',  //商品描述
            'out_trade_no'=>$orderno,  //订单号
            'total_fee'=>$money,  //金额
            'spbill_create_ip'=>'0.0.0.0', //终端IP
            'notify_url'=>'https://zf.ccairport.cn/home/interapi/back_notify', //回调通知url
            'trade_type'=>'PAP', //交易类型
            'contract_id'=>$result['sign_contract_id'], //扣费协议号
            'trade_scene'=>'BUS', //场景信息
            'scene_info'=>json_encode(['scene_info'=>$scene_info],JSON_UNESCAPED_UNICODE),
        ];
        $method = 'HMAC-SHA256'; //通过md5方式签名
        $post_data = signvehicle::sign($post_data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf',$method);
        $curlPost = signvehicle::build($post_data);
        $data = signvehicle::curl_post($url,$curlPost);
        $res =signvehicle::toArray($data);
        //        dump($res);
        return $res;
    }
    public function GetOpenId($id){
        $res = Db::name('user')
            ->field('openid')
            ->where('user_id ='.$id)
            ->find();
        return $res['openid'];
    }
    //扣费回调地址
    public function back_notify(){
        $xml=file_get_contents('php://input', 'r');
        //  Log::write(json_encode($xml,JSON_UNESCAPED_UNICODE),'error');
        $data = signvehicle::toArray($xml);
        $data_sign=$data['sign'];
        // sign不参与签名
        unset($data['sign']);
        $sign= signvehicle::sign($data,pay_config()['key'],$data['sign_type']);
        Cache::set('sign',$sign);
        // 判断签名是否正确  判断支付状态
        if($sign["sign"]===$data_sign){
            $result=true;
        }else{
            $result=false;
        }
        if($result){
            //更新用户订单状态
            Db::name('order_info')
                ->where('out_trade_no ='.$data['out_trade_no'])
                ->update(['trade_state'=>(int)2]);
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
    }
    public function haha(){
        $data = Cache::get('data');
        $data_sign=$data['sign'];
        unset($data['sign']);
        $sign= signvehicle::sign($data,pay_config()['key'],$data['sign_type']);
        // 判断签名是否正确  判断支付状态
        if($sign["sign"]===$data_sign){
            $result=true;
        }else{
            $result=false;
        }
        if($result){
            //更新用户订单状态
            Db::name('order_info')
                ->where('out_trade_no ='.$data['out_trade_no'])
                ->update(['trade_state'=>(int)2]);
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
    }


}